package net.wanho.productManage.dao.impl;

import net.wanho.commons.dao.impl.BaseDAOImpl;
import net.wanho.commons.exception.DAOException;
import net.wanho.commons.exception.DataAccessException;
import net.wanho.productManage.dao.ProductInventoryDAO;
import net.wanho.productManage.po.OrdersDetail;
import net.wanho.productManage.po.ProductInventory;

import java.util.List;

public class ProductInventoryDAOImpl extends BaseDAOImpl<ProductInventory> implements ProductInventoryDAO {
    @Override
    public ProductInventory selectByProductIdAndStoreId(Integer productId, Integer storeId) throws DAOException {
        try {
            String sql = "SELECT \n" +
                    "  INVENTORY_ID inventoryId,\n" +
                    "  PRODUCT_ID \"product.productId\",\n" +
                    "  STORE_ID \"store.storeId\",\n" +
                    "  INVENTORY inventory,\n" +
                    "  UPDATE_TIME updateTime \n" +
                    "FROM\n" +
                    "  product_inventory proinv \n" +
                    "WHERE proinv.PRODUCT_ID = ? \n" +
                    "  AND proinv.STORE_ID = ?";
            Object[] params = {productId,storeId};
            return super.queryForObject(sql,params) ;
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw new DAOException(e.getMessage());
        }
    }

    @Override
    public boolean updateBatch(List<ProductInventory> productInventoryList) throws DAOException {
        try {
            String sql = "UPDATE \n" +
                    "  product_inventory \n" +
                    "SET\n" +
                    "  PRODUCT_ID = ?,\n" +
                    "  STORE_ID = ?,\n" +
                    "  INVENTORY = ?,\n" +
                    "  UPDATE_TIME = NOW() \n" +
                    "WHERE INVENTORY_ID = ?";
            Object[][] params = new Object[productInventoryList.size()][4] ;
            for (int i = 0; i < productInventoryList.size(); i++) {
                ProductInventory productInventory = productInventoryList.get(i);
                params[i][0] = productInventory.getProduct().getProductId() ;
                params[i][1] = productInventory.getStore().getStoreId() ;
                params[i][2] = productInventory.getInventory() ;
                params[i][3] = productInventory.getInventoryId() ;
            }
            return super.jdbcTemplate.updateBatch(sql,params) ;
        } catch (DataAccessException e) {
            e.printStackTrace();
            throw new DAOException(e.getMessage());
        }
    }
}
